
import Vue from "vue";
import $ from "jquery";

import {Activity} from "./activity.js";
import {bdAsr} from "../hos/bdasr.js"; // 导入百度语音识别接口


class BdAsrTest extends Activity {

    /**
     * @param {{name:string,data:{results:Array<string>,result_type:string}}} event
     */
    onAsrResults(event) {
        $(this.find("log")).append(JSON.stringify(event.data) + "<br>");
    }


    onAsrError(event) {
        $(this.find("log")).append("识别错误" + JSON.stringify(event.data) + "<br>");
    }

    onAsrExit(event) {
        $(this.find("log")).append("识别退出" + "<br>");
    }

    onCreate() {
        super.onCreate();
        bdAsr.addResultsObserver(this.onAsrResults, this);
        bdAsr.addErrorObserver(this.onAsrError, this);
        bdAsr.addExitObserver(this.onAsrExit, this);

        new Vue({
            el: this.find("start"),
            methods: {
                click: ()=> {
                    bdAsr.requestAuthorization().then(()=>{
                        bdAsr.start().then((ignore) => {
                            $(this.find("log")).append("请说话..." + "<br>");
                        }, (e)=>{
                            alert("开始失败：" + JSON.stringify(e));
                        });
                    },(e) => {
                        alert("授权失败：" + JSON.stringify(e));
                    });
                }
            }});

        new Vue({
            el: this.find("stop"),
            methods: {
                click: ()=> {
                    bdAsr.stop();
                }
            }});
    }

    onPause() {
        super.onPause();
        bdAsr.stop(); // 取消本次识别
    }

    onDestroy() {
        bdAsr.stop(); // stop并不会移除监听函数
        // 移除相关监听函数
        bdAsr.removeResultsObserver(this.onAsrResults);
        bdAsr.removeExitObserver(this.onAsrExit);
        bdAsr.removeErrorObserver(this.onAsrError);
        super.onDestroy();
    }
}

export {BdAsrTest};
